﻿//-----------------------------------------------------------------------
// <copyright file="DynamicSettingRepository.cs" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings
using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Linq;
using FastNET.CleanAct.Client.CleanEngineData.Entities;
using FastNET.CleanAct.Common.Repository;
using FastNET.CleanAct.Common.Repository.Interfaces.DataInterfaces.Client;
using FastNET.CleanAct.Common.Repository.Interfaces.Repositories.Client;
#endregion

namespace FastNET.CleanAct.Client.CleanEngineData.Repositories
{
    /// <summary>
    /// General repository for managing DynamicSetting
    /// </summary>
    internal class DynamicSettingRepository
        : IDynamicSettingRepository
    {
        #region CTor/DTor

        /// <summary>
        /// Initializes a new instance of the DynamicSettingRepository class
        /// </summary>
        /// <param name="connection">Reference to the common EntityConnection for the repository</param>
        internal DynamicSettingRepository(EntityConnection connection)
        {
            Connection = connection;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a reference to the common EntityConnection for the repository
        /// </summary>
        protected EntityConnection Connection { get; private set; }

        #endregion

        #region IDynamicSettingRepository Members

        /// <summary>
        /// Retrieves all settings associated with a profile
        /// </summary>
        /// <param name="profileID">Profile of the setting group to retrieve or null for the global settings</param>
        /// <returns>List of IDynamicSettingData found</returns>
        public IList<IDynamicSettingData> RetrieveByProfileID(Identity? profileID)
        {
            List<IDynamicSettingData> returnValues = new List<IDynamicSettingData>();

            using (EngineEntities dataSource = new EngineEntities(Connection))
            {
                IEnumerable<DynamicSetting> query = from item in dataSource.DynamicSettingSet where item.ProfileID == profileID select item;

                foreach (DynamicSetting item in query)
                {
                    returnValues.Add(item);
                    dataSource.Detach(item);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves all settings associated with a key name
        /// </summary>
        /// <param name="keyName">Key of the settings to retrieve</param>
        /// <returns>List of IDynamicSettingData found</returns>
        public IList<IDynamicSettingData> RetrieveByKeyName(string keyName)
        {
            List<IDynamicSettingData> returnValues = new List<IDynamicSettingData>();

            using (EngineEntities dataSource = new EngineEntities(Connection))
            {
                IEnumerable<DynamicSetting> query = from item in dataSource.DynamicSettingSet where item.KeyName == keyName select item;

                foreach (DynamicSetting item in query)
                {
                    returnValues.Add(item);
                    dataSource.Detach(item);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves a single setting using the profile ID and the key name
        /// </summary>
        /// <param name="profileID">Profile of the setting group to retrieve or null for the global settings</param>
        /// <param name="keyName">Key of the setting to retrieve</param>
        /// <returns>IDynamicSettingData found or null if the setting does not exist</returns>
        public IDynamicSettingData RetrieveByProfileAndKey(Identity? profileID, string keyName)
        {
            if (string.IsNullOrEmpty(keyName))
            {
                throw new ArgumentNullException("keyName", "Must have a key name to search by");
            }

            using (EngineEntities dataSource = new EngineEntities(Connection))
            {
                if (profileID.HasValue)
                {
                    if (!profileID.Value.CanFitInGuid())
                    {
                        throw new InvalidCastException("profileID must be of type Guid for this repository");
                    }

                    Guid searchID = profileID.Value;
                    return (from
                                item
                                in
                                dataSource.DynamicSettingSet
                            where
                                item.KeyName == keyName &&
                                item.ProfileID.HasValue &&
                                item.ProfileID.Value == searchID
                            select
                                item).SingleOrDefault();
                }

                return (from
                            account
                            in
                            dataSource.DynamicSettingSet
                        where
                            account.KeyName == keyName
                        select
                            account).SingleOrDefault();
            }
        }

        #endregion

        #region IRepository<IDynamicSettingData> Members

        /// <summary>
        /// Retrieves all instances of IDynamicSettingData from the repository
        /// </summary>
        /// <returns>IEnumerable of the requested IData</returns>
        public IList<IDynamicSettingData> Retrieve()
        {
            List<IDynamicSettingData> returnValues = new List<IDynamicSettingData>();

            using (EngineEntities dataSource = new EngineEntities(Connection))
            {
                IEnumerable<DynamicSetting> query = from item in dataSource.DynamicSettingSet select item;

                foreach (DynamicSetting item in query)
                {
                    returnValues.Add(item);
                    dataSource.Detach(item);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves the requested IDynamicSettingData by an Identity
        /// </summary>
        /// <param name="ID">Identity to retrieve the data by</param>
        /// <returns>IData instance or null if one was not found</returns>
        /// <exception cref="InvalidCastException">Thrown if the identity is of the wrong type for this datasource</exception>
        public IDynamicSettingData Retrieve(Identity ID)
        {
            if (!ID.CanFitInGuid())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Guid Type. Currently is {0}.", ID.UnderlyingType()));
            }

            // This has to be done here because LINQ does not support the inline case
            Guid searchID = ID;

            using (EngineEntities dataSource = new EngineEntities(Connection))
            {
                DynamicSetting foundItem = (from
                                                item
                                                in
                                                dataSource.DynamicSettingSet
                                            where
                                                item.SettingID == searchID
                                            select
                                                item).FirstOrDefault();

                if (foundItem != null)
                {
                    dataSource.Detach(foundItem);
                }

                return foundItem;
            }
        }

        /// <summary>
        /// Deletes the requested IDynamicSettingData
        /// </summary>
        /// <param name="Data">IDynamicSettingData to delete from the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        /// <exception cref="InvalidOperationException">Thrown if the IDynamicSettingData is new or already deleted</exception>
        public void Delete(IDynamicSettingData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is DynamicSetting))
            {
                throw new InvalidCastException("Data is not of type DynamicSetting. Cannot delete this object through this repository");
            }

            if (Data.IsNew)
            {
                throw new InvalidOperationException("Data cannot be new before deleting. There is nothing to delete.");
            }

            if (Data.IsDeleted)
            {
                throw new InvalidOperationException("Data already deleted.");
            }

            using (EngineEntities dataSource = new EngineEntities(Connection))
            {
                dataSource.Attach((DynamicSetting)Data);
                dataSource.DeleteObject(Data);
                dataSource.SaveChanges();
            }
        }

        /// <summary>
        /// Saves the requested IDynamicSettingData
        /// </summary>
        /// <param name="Data">IDynamicSettingData to save to the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        public void Save(IDynamicSettingData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is DynamicSetting))
            {
                throw new InvalidCastException("Data is not of type Account. Cannot save this object through this repository");
            }

            if (!Data.IsDirty)
            {
                return;
            }

            using (EngineEntities dataSource = new EngineEntities(Connection))
            {
                if (Data.IsNew)
                {
                    dataSource.AddToDynamicSettingSet((DynamicSetting)Data);
                    dataSource.SaveChanges();
                    dataSource.Detach(Data);
                }
                else
                {
                    dataSource.ApplyPropertyChanges("DynamicSettings", Data);
                    dataSource.SaveChanges();
                }
            }
        }

        /// <summary>
        /// Creates a new instance of IDynamicSettingData
        /// </summary>
        /// <returns>New Instance of IDynamicSettingData</returns>
        public IDynamicSettingData Create()
        {
            return new DynamicSetting();
        }

        #endregion
    }
}